#include "shmsg.h"
#include "los_event.h"
#include "los_task.h"
#include "uart.h"

#define LOSCFG_SHELL_PRIO   3
#define SHELL_CMD_MAX_SIZE 64
EVENT_CB_S g_shellInputEvent;

VOID ShellTaskEntry(VOID)
{
    CHAR buf[SHELL_CMD_MAX_SIZE] = { 0 };
    CHAR* ptr = buf;

    INT8  c;
    PRINTK("OHOS # ");
    while (1) {
        (VOID)LOS_EventRead(&g_shellInputEvent, 0x1, LOS_WAITMODE_AND | LOS_WAITMODE_CLR, LOS_WAIT_FOREVER);

        c = (INT8)UartGetc();
        while (c != 0) {
            UartPutc(c, NULL);

            if (c == '\n') {
                *ptr = '\0';
                ExecCmdline(buf);
                PRINTK("OHOS # ");
                ptr = buf;
            } else {
                if (c == '\r') {
                    /* Ignore */
                } else if ((c == '\b') || (c == 0x7F)) {
                    if (ptr > buf) {
                        ptr--;
                        *ptr = '\0';
                    }
                } else {
                    /* valid character */
                    if ((c >= ' ') && (c <= '~')) {
                        if ((ptr - buf) < sizeof(buf) - 1) {
                            *ptr = c;
                            ptr++;
                        }
                    }
                }
            }
            c = UartGetc();
        }
    }
}

LITE_OS_SEC_TEXT_MINOR UINT32 LosShellInit(VOID)
{
    UINT32 ret;
    UINT32 taskID1;
    TSK_INIT_PARAM_S task1 = { 0 };

    ret = LOS_EventInit(&g_shellInputEvent);
    if (ret != LOS_OK) {
        PRINTK("Init shellInputEvent failed! ERROR: 0x%x\n", ret);
        return ret;
    }

    task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ShellTaskEntry;
    task1.uwStackSize  = 0x1000;
    task1.pcName       = "ShellTaskEntry";
    task1.usTaskPrio   = LOSCFG_SHELL_PRIO;
    ret = LOS_TaskCreate(&taskID1, &task1);
    if (ret != LOS_OK) {
        PRINTK("Create Shell Task failed! ERROR: 0x%x\n", ret);
        return ret;
    }

    return ret;
}
